﻿<?php
/* unicode for json_decode */
function json_encode_uft8($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

/**
 * Khoi tao gio hang
 */
 function cart_init(){
    //unset($_SESSION['cart']);
    if(!isset($_SESSION['cart'])) $_SESSION['cart'] = array();
 }
 add_action("init","cart_init");
 
/**
 * Check cart is empty
 */
function cart_empty(){
   return count($_SESSION['cart'])<=0; 
}


/**
 * Check item in cart
 */
function item_in_cart($_item){
    foreach($_SESSION['cart'] as $key => $item){
        if( $_item->idproduct==$item->idproduct && 
            $_item->color==$item->color && 
            $_item->size==$item->size){
            return array(
                'index' => $key,
                'value' => $item
            );
        }
    }
    return false;
}
 
/**
 * empty cart
 */
 /* clear cart when user logout */
add_action('wp_logout','do_empty_cart');
function do_empty_cart(){
	$_SESSION['order_new'] = true;
    unset($_SESSION['cart']);
}

 /**
  * Get total
  */
function get_total_cart(){
    $total = 0;
    foreach($_SESSION['cart'] as $key=>$item){
        $total+= $item->qty;
    }
    return $total;
}

/**
  * Get total price
  */
function get_total_price(){
    $total_price = 0;
    foreach($_SESSION['cart'] as $key => $item){
        $price = get_post_meta($item->idproduct,'price-tmp', true);
        $sale = get_post_meta($item->idproduct,'sale-price-tmp', true); 
        $total_price += (($sale!="")?$sale:$price)*$item->qty;
    }
	return $total_price;
}
 

/**
 * Add to cart
 */
function add_to_cart($item){
    
    if($cart_item = item_in_cart($item)){
        $index = $cart_item['index']; 
        $_SESSION['cart'][$index]->qty += $item->qty;
    }else{
        $_SESSION['cart'][] = $item;
    }
    $result = array(
        'error' => false,
        'message' => "<div class='alert alert-success fade in'>
                    	<strong>Thành công!</strong> Đã thêm sản phẩm vào giỏ hàng. <a href='".get_permalink(get_page_id("gio-hang"))."'>{ Xem giỏ hàng }</a>
                     </div>",
        'cart_qty' => get_total_cart(),
        'cart_price' => number_format(get_total_price(),0,",",".")
    );
    return $result;
}

 /**
  * Ajax add to cart
  */
function ajax_add_to_cart(){
    $idproduct = $_POST['product'];
    $color = $_POST['chose_color'];
    $size = $_POST['chose_size'];
    $qty = $_POST['quantity'];
	$price=0;
    
    $item = new stdClass();
    $item->idproduct = $idproduct;
    $item->color = $color;
    $item->size = $size;
    $item->qty = $qty;
	$item->p_coupon=$price;
    
    header('Content-Type: application/json');    
    $result = add_to_cart($item);
    echo json_encode($_SESSION['cart']);
    die();
}
add_action('wp_ajax_nopriv_add-to-cart', 'ajax_add_to_cart');
add_action('wp_ajax_add-to-cart', 'ajax_add_to_cart');


 /**
  * Ajax remove_item_cart
  */
function ajax_remove_item_cart(){
    $key = $_POST['key'];
    unset($_SESSION['cart'][$key]);
    
    header('Content-Type: application/json');   
    echo json_encode(array(
        'error' => false,
        'message' => "",
        'subtotal_price' => number_format(get_total_price(),0,",","."),
        'total' => get_total_cart()
    ));
    die();
}
add_action('wp_ajax_nopriv_remove-item-cart', 'ajax_remove_item_cart');
add_action('wp_ajax_remove-item-cart', 'ajax_remove_item_cart');

 /**
  * Ajax update_to_cart
  */
function ajax_update_to_cart(){
    $key = $_POST['key'];
    $qty = $_POST['qty'];
    $_SESSION['cart'][$key]->qty=$qty;
    $item = $_SESSION['cart'][$key];
    
    $price = get_post_meta($item->idproduct,"price-tmp", true);
    $sale = get_post_meta($item->idproduct,"sale-price-tmp", true);
    $_price = ($sale!="")?$sale:$price;
    
    echo json_encode(array(
        'error' => false,
        'message' => "",
        'subtotal_price' => number_format(get_total_price(),0,",","."),
        'total' => get_total_cart(),
        'total_price' => number_format($_price*$qty,0,",","."),
    ));
    
    die();
}
add_action('wp_ajax_nopriv_update-to-cart', 'ajax_update_to_cart');
add_action('wp_ajax_update-to-cart', 'ajax_update_to_cart');


 /**
  * User login
  */
function ajax_user_login(){
	$page_id = $_POST['page_id'];
    $result = array(
        'error' => true,
        'alert' => "<div class='alert fade in'>
                    	<strong>Lỗi!</strong> Tài khoản hoặc mật khẩu không đúng.
                    </div>",
		'link' => null
    );    
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    if($username=="" || $password==""){
        echo json_encode($result);exit(0);
    }
    
    $info_log['user_login']     = $username;
    $info_log['user_password']  = $password;
    
    $user = wp_signon( $info_log, false );
    if(is_wp_error($user)){
        echo json_encode($result);exit(0);
    }
    
	$link = get_permalink($page_id);
	if($page_id==133) $link = get_permalink(get_page_id('thanh-toan'));
	elseif($page_id==1) $link = home_url();

    $result = array(
        'error' => false,
        'alert' => "<div class='alert fade in success'>
                    	<strong>Thành công!</strong> Đăng nhập thành công!
                    </div>",
		'link' => $link,			
    );
    
    echo json_encode($result);
    die();
}
add_action('wp_ajax_nopriv_user-login', 'ajax_user_login');
add_action('wp_ajax_user-login', 'ajax_user_login');

/**
 * Ajax chekcout
 */
function ajax_checkout(){
	global $current_user,$woo_options;
	
    $payment_id = $_POST['payment'];
	
	/* Code order */
	$orderCode = "DH".date("Ymd").(is_user_logged_in()?strtoupper($current_user->user_login):'GUEST');
	
	/* Get post customer data */
    $session_customers = $_SESSION['customers'];
	$customer_receiv = new stdClass();
	foreach($session_customers['receiv'] as $key => $value){
		$customer_receiv->{$key} = $value;
	}
	$customer_buy = new stdClass();
	foreach($session_customers['buy'] as $key => $value){
		$customer_buy->{$key} = $value;
	}
	
	/* Default status order */
	list($order_status) = get_terms('order-status',array('hide_empty'=>false,'orderby'=>'custom_sort','order'=>'asc'));
	
	/* Payment */
	$order_payment = get_term_by('id',$payment_id ,'order-payment');
	
	/* Order detail */
	$orders = array();
	foreach($_SESSION['cart'] as $key => $item){
		$item->url = get_edit_post_link($item->idproduct);
		list($item->image) = wp_get_attachment_image_src(get_post_thumbnail_id($item->idproduct),"thumbnail");
		$item->name = get_the_title($item->idproduct);
		
		$term_size = get_term_by('id',$item->size,'size');
		$item->sizename = $term_size->name;
		
		$term_color = get_term_by('id',$item->color,'color');
		$item->colorname = $term_color->name;
		$item->colorhex = get_tax_meta($item->color,'color');
		$color_img = get_tax_meta($item->color,'image');
        if(isset($color_img['id'])){
		  list($item->colorimg) = wp_get_attachment_image_src($color_img['id'],"thumbnail");
        }
		
		$item->price = get_post_meta($item->idproduct,"price-tmp",true);
		$item->sale = get_post_meta($item->idproduct,"sale-price-tmp",true);
		
		$orders['checkout'][] = $item;
	}
	$orders['order_price'] = get_total_price();
	$orders['order_payment'] = $order_payment->name;
	$orders['order_date'] = date("d/m/Y");
	
    
    /* Post content */
    $info = array(
        'fullname' => 'Họ tên',
        'phone' => 'Điện thoại',
        'email' => 'Email',
        'local' => 'Tỉnh/Thành',
        'district' => 'Quận/Huyện',
        'address' => 'Địa Chỉ'
    );
    
	/* Insert post */
	$my_order = array(
	  'post_title'		=> $orderCode,
	  'post_type'		=> 'orders',
	  'post_content'	=> '',
	  'post_status'		=> 'publish',
	  'post_author'		=> (is_user_logged_in()?$current_user->ID:1)
	);
	$idpost = wp_insert_post( $my_order );
	wp_update_post(array('ID'=>$idpost,'post_title'=>$orderCode.$idpost));
	/* update customer info */
	if(isset($_SESSION['customers']['other_address']) && $_SESSION['customers']['other_address']=='yes'){
		update_post_meta($idpost, 'order-customer' , json_encode_uft8($customer_receiv));
	}
	update_post_meta($idpost, '_customer' , json_encode_uft8($customer_buy));
	
	/* update message */
	update_post_meta($idpost, '_message' , $session_customers['message']);
	
	/* update order detail */
	update_post_meta($idpost, 'order-detail' , json_encode_uft8($orders));
	
	/* update order status */
	update_post_meta($idpost, 'order-status' , $order_status->term_id);
	wp_set_object_terms($idpost,array($order_status->slug),'order-status');
	
	/* update order payment */
	wp_set_object_terms($idpost,array($order_payment->slug),'order-payment');
	
    /* Return Content */    
    $alert2 = "
    <div style='font-size:14px; color: #004080;'>
        <p><strong>Cám ơn quý khách đã đặt hàng tại  <a href='".home_url()."'>".get_bloginfo()."</a>!</strong></p>
    </div>";    
    ob_start();
    ?>

    <div class="main-title">
    	 <?php $args =array("fields"=>"all"); ?>	
    	 <?php $term_all=get_terms("danh-muc", $args ); ?>  
    	<div style="width:100%;background-color:#000000;color:white;height:50px;text-align:center;">
        	<ul style="list-style:none">
            
            	<li style="float:left;margin-right:60px;padding-top:15px;"><a style="color:white;font-size:12px;font-weight:bold;" href="<?php echo get_post_type_archive_link("san-pham") ?>">Shop</a></li>
                <li style="float:left;margin-right:60px;padding-top:15px;"><a style="color:white;font-size:12px;font-weight:bold;" href="<?php echo get_permalink(get_page_id("cham-soc-khach-hang")) ?>">Chăm sóc khách hàng</a></li>
                <li style="float:left;margin-right:60px;padding-top:15px;"><a style="color:white;font-size:12px;font-weight:bold;" href="<?php echo get_permalink(get_page_id("truyen-thong")) ?>">Tryền thông</a></li>
                <li style="float:left;margin-right:60px;padding-top:15px;"><a style="color:white;font-size:12px;font-weight:bold;" href="<?php echo get_post_type_archive_link("tin-tuc") ?>">Tin tức</a></li>
            </ul>
        </div>
        <div style="width:100%;text-align:center;margin-top:10px;"><i style="background-image:none;background-color:rgb(255,255,51);font-size:12px;font-family:Arial,Helvetica,sans-serif;background-repeat:repeat repeat;margin-top:30px;">Đây là email tự động, quý khách vui lòng không trả lời vào email này!</i> </div> 
        <h4 style="clear:both">Xác nhận đơn hàng : <?php echo $orders['order_payment'] ?> </h4>
        <div style="height:1px;width:100%;background-color:#f5f5f5"></div>
		</div>
	    <div style="padding:0 35px 10px;border-bottom:4px #f5f5f5 solid;border-left:5px #f5f5f5 solid;border-right:5px #f5f5f5 solid;width:89%;">
		<div style="margin-top:20px;">Kính chào Quý khách <?php echo $current_user->data->display_name; ?></div><br />
        <?php //echo $orderCode.$idpost;?>
        <p style="mar">Vainia vừa nhận được đơn hàng có mã số <strong><?php echo $orderCode.$idpost;?></strong> của Quý khách. Bằng email này, Vainia xin xác nhận đơn hàng nêu trên và chúng 
        tôi sẽ <strong>không thực hiện bất cứ cuộc gọi xác nhận nào</strong> trừ khi có trục trặc với đơn hàng hay cần làm rõ thêm thông tin.</p></br>
        <p style="margin:1px;">Đơn hàng sẽ được thực hiện và chuyển đến quý khách trong vòng:</p>
        <p style="margin:1px;"> - Đối với địa chỉ giao hàng tại thành phố Hồ Chí Minh: <strong>dự kiến trong 1-3 ngày làm việc</strong></p>
        <p style="margin:1px;"> - Đối với địa chỉ giao hàng tại các khu vực khác: <strong>dự kiến trong 2-8 ngày làm việc</strong></p>
        <p>
        Thời gian giao hàng cụ thể sẽ được thông báo qua email hoặc tin nhắn khi đơn hàng đã sẵn sàng để giao.
        Quá trình thực hiện đơn hàng sẽ được liên tục cập nhật qua email. Vui lòng kiểm tra hộp thư của quý khách thường xuyên. <br />
        </p>
        <p>Sau đây là thông tin chi tiết về đơn hàng:</p>
        
        <div style="margin-top:20px;width:100%;border:1px solid #e8f0f2;">
        	<table width="100%" cellspacing="0" cellpadding="5" border="0" style="border:1px solid rgb(222,226,227)">
                                <tbody><tr>
                                  <td style="font-size:12px;font-family:Arial,Helvetica,sans-serif;background-image:none;background-color:rgb(220,239,245);font-weight:bold;text-align:center;background-repeat:repeat repeat">Sản phẩm</td>
                                  <td style="font-size:12px;font-family:Arial,Helvetica,sans-serif;background-image:none;background-color:rgb(220,239,245);font-weight:bold;text-align:center;background-repeat:repeat repeat">Mã sản phẩm</td>
                                  <td style="font-size:12px;font-family:Arial,Helvetica,sans-serif;background-image:none;background-color:rgb(220,239,245);font-weight:bold;text-align:center;background-repeat:repeat repeat">Giá <br>
                                    VNĐ</td>
                                  <td style="font-size:12px;font-family:Arial,Helvetica,sans-serif;background-image:none;background-color:rgb(220,239,245);font-weight:bold;text-align:center;background-repeat:repeat repeat">Số Lượng</td>
                                  <td style="font-size:12px;font-family:Arial,Helvetica,sans-serif;background-image:none;background-color:rgb(220,239,245);font-weight:bold;text-align:center;background-repeat:repeat repeat">Thành tiền<br>
                                    VNĐ</td>
                                </tr>
                                <?php foreach($_SESSION['cart'] as $key=> $item){ $post = get_post($item->idproduct);?>
                                <tr>
                                  <td valign="top" style="font-size:11px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227)"><?php echo $post->post_title; ?></td>
                                  <td valign="top" style="font-size:11px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227)"><?php echo get_post_meta($post->ID,"code-sku",true); ?></td>
                                  <td valign="top" style="font-size:11px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227)"><?php echo show_format_price($item->idproduct,'price_one');$_price=get_one_price($item->idproduct); ?></td>
                                  <td valign="top" style="font-size:11px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227)"><?php echo $item->qty;?></td>
                                  <td valign="top" style="font-size:11px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227)"><?php echo show_format_price($item->idproduct,'price_one'); ?></td>
                                </tr>
                                <?php } ?>
                                <tr>
                                  <td valign="top" align="right" style="font-size:12px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227)" colspan="3"><b>Tổng cộng</b><br>
                                  <i>đã bao gồm chi phí đóng gói, giao hàng và hàng cồng kềnh (nếu có)</i></td>
                                  <?php
								    if($_SESSION['cart'][0]->price_coupon==0)
									{
										$sub_PRICE=number_format($_price['price_one']*$item->qty,0,",",".")." VNĐ";
									}
									else
									{
										$sub_PRICE=$_SESSION['cart'][0]->price_coupon;
									}
								   ?>
                                  <td valign="top" style="font-size:12px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227);font-weight:bold" colspan="2"><?php echo $sub_PRICE;?></td>
                                </tr>
                                
                                <tr>
                                  <td valign="top" align="right" style="font-size:12px;font-family:Arial,Helvetica,sans-serif;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(222,226,227);font-weight:bold;text-align:left" colspan="5">Thông tin giao hàng:  <?php echo get_post_meta($post->ID,"_message",true);?> </td>
                                </tr>
                </tbody></table>
                <table>
                  <tr>
                    <td valign="top" bgcolor="#ffffff" style="line-height:18px;font-size:12px;font-family:Arial,Helvetica,sans-serif;padding:0px 15px">
                        <div style="margin-top:10px;"><strong>Ngoài ra </strong>, quý khách còn có thể xem thêm phần hỏi đáp tại website <a target="_blank" href="<?php echo get_permalink(get_page_id("cham-soc-khach-hang")) ?>" rel="nofollow"><?php echo get_permalink(get_page_id("cham-soc-khach-hang")) ?></a> nếu có thắc mắc về chính sách giao hàng, hậu mãi và chính sách đổi trả hàng. </div>
                        <div>Một lần nữa, cám ơn Quý khách đã mua sắm tại <b>Vania.com.vn</b>. Hi vọng chúng tôi đã mang lại cho Quý khách những trải nghiệm mua sắm thật tuyệt vời.</div>
                        <div><br>
                          Trân trọng,<br>
                      <b>Đội ngũ Vania.com.vn</b></div></td>
                  </tr>
                  <tr>
                      <td valign="top" bgcolor="#ffffff" style="line-height:18px;font-size:12px;font-family:Arial,Helvetica,sans-serif;padding:15px 15px 0px"><div style="padding:0px;margin:0px 0px 20px"><b>Mời Quý khách tham khảo những sản phẩm được quan tâm nhất tại Lazada</b></div></td>
                  </tr>
                  <tr>
                      <td valign="top" bgcolor="#ffffff" style="line-height:18px;font-size:12px;font-family:Arial,Helvetica,sans-serif;padding:0px 15px 15px"><table width="600" cellspacing="0" cellpadding="0" border="0">
  					<?php
		            
								$args = array(
								'post_type' => 'san-pham',
								'posts_per_page' =>8,
								'tax_query' => array(
									array(
										'taxonomy' => 'san-pham-mail',
										'field' => 'slug',
										'terms' => array('email-marketing')
									)
								)
							);
                    $wp_query = new WP_Query($args);
                     while ( $wp_query->have_posts() ) :  $wp_query->the_post();
					   list($thumb) = wp_get_attachment_image_src(get_post_thumbnail_id(),"medium");
					     $list_id=json_decode($post->post_excerpt); ?>
					   
                       
                        
                            <div style="width:140px;float:left;margin:20px 0px 0px 5px;">
                            	<div><a href="<?php echo get_permalink($list_id[0]) ?>" title="<?php the_title(); ?>"><img width="140" height="140" src="<?php echo $thumb ?>" alt="<?php the_title() ?>" title="<?php the_title() ?>" /></a></div>
                            	<div style="color:#3A3A3A;font-weight:bold;font-size:13px;text-align:center"><?php the_title(); ?></div>
                            </div>
                      <?php endwhile;wp_reset_query(); ?>  
                      <div style="clear:both"></div>
					</td>
                       
                    </tr>
                    <?php exit(); ?>
                    
                    
                </table>
                <table style="background-color:#dddddd;width:100%;">
                	<tr>
                    	 <td valign="top" align="center" style="padding:10px 0 0 10px;font-family:Arial,Helvetica,sans-serif;font-size:11px;color:rgb(13,13,13)"><span style="display:block;text-align:center;text-transform:uppercase;font-size:12px;color:rgb(237,28,36);margin:0px 0px 5px;font-weight:bold">Xem tất cả Danh mục</span>
                        <div style="padding:0px;margin:0px;line-height:18px">
                        	<?php foreach ($term_all as $v) {?>
                        	| <a target="_blank" href="<?php echo get_term_link($v,"danh-muc") ?>" style="text-decoration:none;color:rgb(13,13,13)" title="<?php echo $v->name ?>" rel="nofollow"><span style="color:rgb(13,13,13)"><?php echo $v->name ?></span></a>
                            <?php } ?>
                            </div>
                          <br>
                       </td>
                    </tr>
                </table>
        
        </div>
        <div style="width:100%;height:85px;text-align:center;background-color:#000;color:#FFF;padding-top:10px;padding-bottom:10px;font-size:12px;">
        	<div style="font-weight:bold;font-size:13px;"> Công ty Cổ Phần Đầu Tư Thương Mại Vania </div>
            <div style="font-size:11px;"> 344 Nguyễn Đình Chiểu, phường 4, quận 3, Hồ Chí Minh </div>
            <div style="font-size:11px;"> Hotline: (08) 3 832 9568  | Fax: (08) 3 7301 841 | E-mail: <span style="color:#F30 !important">chamsockhachhang@vania.com.vn </span> </div>
            <div style="font-size:11px;"> Đường dây nóng : <strong style="color:#F30;">0909 335 035</strong> </div>  
        </div>

			<hr style="clear:both;"/>

            <div class="cb"></div>           
        </div>        
        
    </div>
    </div>
    <?php
    $_content = ob_get_clean();

    
    /* Send mail */
      $admin_email = $woo_options['woo_contactform_email'];
      wp_mail($admin_email,"Thông tin đơn hàng ".$orderCode.$idpost,$_content);
      wp_mail($_SESSION['customers']['buy']['email'],"Thông tin đơn hàng ".$orderCode.$idpost,$alert2.$_content);   
	
    /* Empty cart */
    do_empty_cart();
	/* Empty cart */
    
	header('Content-Type: application/json');   
    echo json_encode(array(
        'error' => false,
        'message' => "",
        'return_link' => get_permalink($idpost),
		//'content' =>$_content
    ));
	die();
}
add_action('wp_ajax_nopriv_checkout', 'ajax_checkout');
add_action('wp_ajax_checkout', 'ajax_checkout');



function ajax_checkcaptcha(){
	$code = $_SESSION['code'];
	if($code==$_GET['contactCode']){
		echo json_encode(true);
	}else{
		echo json_encode(false);
	}
	die();
}
add_action('wp_ajax_nopriv_captcha', 'ajax_checkcaptcha');
add_action('wp_ajax_captcha', 'ajax_checkcaptcha');



/**
 * Xu ly mua nhanh
 */
function ajax_save_order(){
	global $current_user;
	$error = false;
	$info = array(
        'fullname' => 'Họ tên',
        'phone' => 'Điện thoại',
        'email' => 'Email',
        'local' => 'Tỉnh/Thành',
        'district' => 'Quận/Huyện',
        'address' => 'Địa Chỉ'
    );	
	$datas = $_POST;
	foreach($info as $key=>$value){
		if($datas[$key]==""){
			$error = true;
			break;
		}
	}
	
	if(!$error){
		$payment_id = $_POST['payment'];
		
		/* Default status order */
		list($order_status) = get_terms('order-status',array('hide_empty'=>false,'orderby'=>'custom_sort','order'=>'asc'));
		
		/* Payment */
		$order_payment = get_term_by('id',$payment_id ,'order-payment');
		
		/* Get post customer data */
		$customer_buy = new stdClass();
		foreach($info as $key => $value){
			$customer_buy->{$key} = $datas[$key];
		}
		
		$orders = array();
		$item = new stdClass();
		$item->idproduct = $datas['id_product'];
		$item->qty = $datas['quantity'];
		$item->size = $datas['size'];
		$item->color = $datas['color'];
		
		$item->url = get_edit_post_link($item->idproduct);
		list($item->image) = wp_get_attachment_image_src(get_post_thumbnail_id($item->idproduct),"thumbnail");
		$item->name = get_the_title($item->idproduct);
		
		$term_size = get_term_by('id',$item->size,'size');
		$item->sizename = $term_size->name;
		
		$term_color = get_term_by('id',$item->color,'mau');
		$item->colorname = $term_color->name;
		$item->colorhex = get_tax_meta($item->color,'color');
		$color_img = get_tax_meta($item->color,'image');
		list($item->colorimg) = wp_get_attachment_image_src($color_img['id'],"thumbnail");
		
		$item->price = get_post_meta($item->idproduct,"price-tmp",true);
		$item->sale = get_post_meta($item->idproduct,"sale-price-tmp",true);
			
		$orders['checkout'][] = $item;
		$orders['order_price'] = (($item->sale!="")?$item->sale:$item->price);
		$orders['order_payment'] = $order_payment->name;
		$orders['order_date'] = date("d/m/Y");
		
		
		/* Code order */
		$orderCode = "DH".date("Ymd").(is_user_logged_in()?strtoupper($current_user->user_login):'GUEST');
		
		$my_order = array(
		  'post_title'		=> $orderCode,
		  'post_type'		=> 'orders',
		  'post_content'	=> '',
		  'post_status'		=> 'publish',
		  'post_author'		=> (is_user_logged_in()?$current_user->ID:1)
		);
		$idpost = wp_insert_post( $my_order );
		wp_update_post(array('ID'=>$idpost,'post_title'=>$orderCode.$idpost));
		/* update customer info */
		update_post_meta($idpost, '_customer' , json_encode_uft8($customer_buy));
		
		/* update message */
		update_post_meta($idpost, '_message' , $datas['message']);
		
		/* update order detail */
		update_post_meta($idpost, 'order-detail' , json_encode_uft8($orders));
		
		/* update order status */
		update_post_meta($idpost, 'order-status' , $order_status->term_id);
		wp_set_object_terms($idpost,array($order_status->slug),'order-status');
		
		/* update order payment */
		wp_set_object_terms($idpost,array($order_payment->slug),'order-payment');
		
		header('Content-Type: application/json');
		echo json_encode(array(
			'error'=>false,
			'message' => '<div class="alert alert-success"><strong>Thành công! </strong>Đơn hàng đã gửi thành công.</div>',
		));
	}else{
		echo json_encode(array(
			'error'=>true,
			'message' => '<div class="alert alert-error"><strong>Lỗi! </strong>Hãy nhập đầu đủ thông tin vò các trường bắt buộc.</div>',
		));
	}
    die();
}
add_action('wp_ajax_nopriv_save-order', 'ajax_save_order');
add_action('wp_ajax_save-order', 'ajax_save_order');


/**
 * Filter product
 */
function ajax_get_list_product(){
	global $woo_options, $loop, $wp_query;
	$query = array(
		'post_type' => 'san-pham',
		'orderby' => 'date',
		'order' => 'desc',
		'posts_per_page' => $woo_options['woo_products_per_page'],
		'paged' => isset($_REQUEST['page'])?$_REQUEST['page']:1,
		'status' => array('publish','private'),
	);	
	// Get request
	$requests = array('danh-muc','muc-gia','mau');
	foreach($requests as $parram){
		if(isset($_REQUEST[$parram]) && $_REQUEST[$parram] != NULL){
			$query['tax_query'][] = array(
				'taxonomy' => $parram,
				'field' => 'id',
				'terms' => $_REQUEST[$parram]
			);
		}
	}
	$wp_query = new WP_Query($query);
	if($wp_query->have_posts()){
		?>
		<div class="ar navigation ajax-navi">
			<?php woo_pagination(array('type' => 'list'));?>
		</div>
		<div id="category-product" class="wrap-products">
			<div class="products">
				<?php $loop=0; while($wp_query->have_posts()) { $wp_query->the_post();?>
						<?php get_template_part("templates/loop","product");?>
				<?php  $loop++; } ?>
			</div>
			<div class="clearfix"></div>
			
			<div class="ar navigation  ajax-navi">
				<?php woo_pagination(array('type' => 'list'));?>
			</div>
		</div>
		<script>
		jQuery(function($){
			$(".ajax-navi .pagination ul li a").click(function(){
				var loading = $("<img />").attr({"src":"<?php echo get_template_directory_uri()?>/functions/images/ajax-loader.gif"});
				$(this).prepend(loading);
				var link = "<?php echo admin_url("admin-ajax.php");?>";
				var datas = <?php echo json_encode($_REQUEST);?>;
				datas.page = this.href.replace(/(.*)admin-ajax.phppage\//,"").replace(/\/\?action=(.*)/,"");
				$.get(link, datas, function(rdata){
					$("#wrap-list-product").html(rdata);
					$(".to-top a").click();
				});
				return false;
			});
		})
		</script>
		<?php
		wp_reset_query();
	}else{ ?>
		<h6 class="ac"><em>Không tìm thấy sản phẩm nào!</em></h6>
	<?php }
	die();
}
add_action('wp_ajax_nopriv_get-list-product', 'ajax_get_list_product');
add_action('wp_ajax_get-list-product', 'ajax_get_list_product');




/**
 * AJAX WISHLIST
 */
function check_proudct($id_product,$id_user)
{
	$list_like=get_user_meta($id_user,"list-like-post",true);
	$arr = explode(",",$list_like);
	return $arr;
	foreach ($arr as $v=> $k)
	{
		if($arr[$v]==$id_product)
		 return false;
	}
}
function add_wish_list()
{
	$id_product=$_POST['id_product'];
	$size=$_POST['id_size'];
	$id_user=$_POST['id_user'];
	$time=$_POST['time'];
	$data=array();

	$list_like=get_user_meta($id_user,"list-like-post",true);
	if($list_like==NULL  || $list_like=="")
	{
		$arr=array("id_user"=>$id_user,"id_product"=>$id_product,"size"=>$size,"time"=>$time);
		$data[]=$arr;
		update_user_meta($id_user,"list-like-post",$data);
	}
	else
	{	
		$arr=array("id_user"=>$id_user,"id_product"=>$id_product,"size"=>$size,"time"=>$time);
		foreach ($list_like as $v)
		{
			if(in_array($size,$v))
			{
			   $flag=true;
			   break;
			}
		}
		if($flag!=true)
		{
			array_push($list_like,$arr);
			update_user_meta($id_user,"list-like-post",$list_like);
		}
	}
	die();
}
add_action('wp_ajax_nopriv_add_wish_list', 'add_wish_list');
add_action('wp_ajax_add_wish_list', 'add_wish_list');

function remove_list_yes()
{
   $id_size=$_POST['id_size'];
   $id_user=$_POST['id_user'];
   	
   $list_like=get_user_meta($id_user,"list-like-post",true);
   foreach ($list_like  as $k =>  $v)
   {
	   if($v["size"]==$id_size)
	   {
		   unset($list_like[$k]);
		   break;
	   }
   }
	update_user_meta($id_user,"list-like-post",$list_like);
	die();
}
add_action('wp_ajax_nopriv_remove_list_yes', 'remove_list_yes');
add_action('wp_ajax_remove_list_yes', 'remove_list_yes');



function ajax_email_advand()
{
	global $post;
	$flag=1;
	$email=$_REQUEST['email'];
			$args = array(
			'post_type' => 'email',
			'posts_per_page' =>-1,
			'meta_key'=> 'search-email'
		);
		$the_query = new WP_Query($args);
		while ( $the_query->have_posts() ) :  $the_query->the_post();
	
		$data_email=get_post_meta($post->ID,"search-email",true);
			if($email===$data_email)
			{
				$messs="Email này đã tồn tại";
				$flag=0;
				break;
			}
		 endwhile;wp_reset_query();   
		 
		 if($flag==1)
		 {
			 	$my_post = array(
				  'post_title'    => $email,
				  'post_status'   => 'publish',
				  'post_author'   => 1,
				  'post_type' 	  => 'email'	
				);
				$id=wp_insert_post($my_post,true);
				var_dump(is_wp_error($id));
				$flag=1;
				$messs="";
		 }
		 header('Content-Type: application/json');   
		 echo json_encode(array(
			'error' => $flag,
			'message' => $messs,
		));
   		 die();                  
}
add_action('wp_ajax_nopriv_ajax_email_advand', 'ajax_email_advand');
add_action('wp_ajax_ajax_email_advand', 'ajax_email_advand');


function ajax_coupon()
{
	global $current_user , $post;
	if($_POST['flag_data']=="coupon_user")
	{
		$price_coupon_user=100000;
		$tmp_price=get_total_price()-100000;
	    $price= number_format($tmp_price,0,",",".")." VNĐ";
		foreach ($_SESSION['cart'] as $v)
		{
			$v->price_coupon=$price;
		}
		update_user_meta($current_user->ID,"coupon-code","");
		update_user_meta($current_user->ID,"flag-coupon","0");
		$flag="new";
	}
	else
	{
		$data_coupon=$_POST['data_coupon'];
		
		$args = array(
			'post_type' => 'coupons',
			'meta_key'=> 'code_coupon',
			'meta_value'=> $data_coupon,
			'author' =>$current_user->ID
		);
		$the_query = new WP_Query($args);
		while ( $the_query->have_posts() ) :  $the_query->the_post();	
		$method=get_post_meta($post->ID,'coupon_type',true);
		$value=get_post_meta($post->ID,'coupon_value',true);
		$num_coupon=get_post_meta($post->ID,'coupon_number1',true);
		if($num_coupon>0)	
		{
			if($value!=NULL || $value!="")
			{
				if($method=="on")
				{
				   $tmp_price=(get_total_price()*$value)/100;
				   $tmp_price_one= number_format($tmp_price,0,",",".")." VNĐ";
				   $price=get_total_price()-(get_total_price()*$value)/100;
				   $price= number_format($price,0,",",".")." VNĐ";
				   update_post_meta($post->ID,'coupon_number1',$num_coupon-1);
				   $flag="birthay"; 
				}
				else
				{
				   $price=get_total_price()-$value;
				   $tmp_price_one= number_format($value,0,",",".")." VNĐ";
				   update_post_meta($post->ID,'coupon_number1',$num_coupon-1);
				   $flag="birthay";
				}
				foreach ($_SESSION['cart'] as $v)
				{
					$v->price_coupon=$price;
				}
			}
			$impo=true;
		}
		else
		{
			$impo=false;
		}
		endwhile;wp_reset_query();
	}
	header('Content-Type: application/json');   
	echo json_encode(array(
		'flag' => $flag,
		'price' => $price,
		'tmp_price'=>$tmp_price_one,
		'impo' =>$impo
	));
   		 die();
	
}
add_action('wp_ajax_nopriv_ajax_coupon', 'ajax_coupon');
add_action('wp_ajax_ajax_coupon', 'ajax_coupon');



/**
 * @author: phongnd
 * Khoi tao order_cart (gio hang)
 */
 function order_cart_init(){
    if(!isset($_SESSION["order_cart"])) $_SESSION["order_cart"] = array();
 }
 add_action("init","order_cart_init");
 
/**
 * @author: phongnd
 * Check order_cart is empty
 */
function order_cart_empty(){
   return count($_SESSION["order_cart"])<=0; 
}

/**
 * @author: phongnd
 * empty cart
 */
 /* clear cart when user logout */
function do_empty_order_cart(){
	$_SESSION["order_new222"] = true;
    unset($_SESSION["order_cart"]);
}
add_action("wp_logout","do_empty_order_cart");



/**
 * @author: phongnd
 * Check item in cart
 */
function item_in_order_cart($_item){
    foreach($_SESSION["order_cart"] as $key => $item){
        if( $_item->goods_id==$item->goods_id){
            return array(		 
				"index" => $key, 
				"value" => $item 
            );
        }
    }
    return false;
}


/**
 * @author: phongnd
 * Add to cart
 */
function add_to_order_cart($arrGoodsInfo){
    
    if($cart_item = item_in_order_cart($arrGoodsInfo)){
        $index = $cart_item["index"]; 
        $_SESSION["order_cart"][$index]->qty += $arrGoodsInfo->qty;
    }else{
        $_SESSION["order_cart"][] = $arrGoodsInfo;
    }
    $result = array(
        "error" => false,
        "message" => "<div class='alert alert-success fade in'>
                    	<strong>Thành công!</strong> Đã thêm sản phẩm vào giỏ hàng. <a href='".get_permalink(get_page_id("gio-hang"))."'>{ Xem giỏ hàng }</a>
                     </div>",
        "cart_qty" => get_total_cart(),
        "cart_price" => number_format(get_total_price(),0,",",".")
    );
    return $result;
}


/**
 * ajax_update_order_cart_qty
 * @author: phongnd - Add to cart
 * 
 */
function ajax_update_order_cart_qty(){
    $key = $_POST['key'];
    $qty = $_POST['qty'];
    $_SESSION['order_cart'][$key]->qty=$qty;
    $item = $_SESSION['order_cart'][$key];
	
    $price = 123;//get_post_meta($item->goods_id,"cost-deal", true);
    //$strTotalPrice = 
    echo json_encode(array(
        'error' => false,
        'message' => "",
        'total' => 123,
        'total_price' => number_format($price*$qty,0,",","."),
    ));
    
    die();
}
add_action('wp_ajax_nopriv_update-order-cart-qty', 'ajax_update_order_cart_qty');
add_action('wp_ajax_update-order-cart-qty', 'ajax_update_order_cart_qty');
 
?>

